<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2020/4/30
 * Time: 22:47
 */

namespace app\admin\controller;


use app\common\model\BusInquiry;
use app\common\model\BusInquiryDetail;
use app\common\model\BusInquiryDetailSupplier;
use app\common\model\BusInquirySuppliers;
use app\common\model\BusPurchaseDetail;
use app\common\model\BusSalesDetail;
use app\common\model\SalesCompany;
use app\common\model\SuppliersCompany;
use app\common\model\SysConfig;
use app\common\model\SysUser;
use think\db\exception\DataNotFoundException;
use think\db\exception\ModelNotFoundException;
use think\Exception;
use think\exception\DbException;
use think\exception\PDOException;

class Inquiry extends Admin
{
    protected $quiltyChoose = [
        'service'=>'qulity_service_price',
        'org'=>'qulity_org_price',
        'matching'=>'qulity_matching_price',
        'complete'=>'qulity_complete_price',
        'suitable'=>'qulity_suitable_price'
    ];

    /**
     * 获取公司列表
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getList(){
        $page = input('page', 1);
        $limit = input('limit', 20);
        $due_date = input('due_date','');
        $state = input('state','','trim');
        $role_id = input('opt_role_id','','trim');
        $param = $this->getParam();
        if($due_date){
            $date_arr = explode(' - ',$due_date);
            if(!empty($date_arr)){
                $param['add_datetime'] = ['between', [trim($date_arr[0]), date('Y-m-d', strtotime ("+1 day", strtotime(trim($date_arr[1]))))]];
            }
        }
        if($state || $state !== ''){
            if($state == 2){
                $param['sale_price_state'] = ['>',0];
            }else{
                $param['sale_price_state'] = 0;
            }
        }
        $model = new BusInquiry();
        $model->where(['deadline_datetime'=>['<',date('Y-m-d H:i:s')],'sale_price_state'=>0])->setField('state',3);
        $count = $model->where($param)->count();
        if($page > ceil($count/$limit)){
            $page = ceil($count/$limit);
        }
        $lst = $model->with(['sales_company','quote_suppliers'])->where($param)->order('add_datetime desc,id desc')->page($page,$limit)->select();
        $times = date('Y-m-d H');
        foreach ($lst as $item){
            $item['city_info'] = $item['province'].$item['city'];
            $item['is_expired'] = $item['deadline_datetime']<$times ? 1 :0;
            $item['has_quote'] = count($item['quote_suppliers']);
            $item['sum_quote'] = count($item['bus_to_company_ids']);
            $item['opt_role_id'] = $role_id;
        }
        return json_tab_msg($count,$page,$lst);
    }


    public function getDetailInfo(){
        $id = input('id');
        $model = new BusInquiry();
        $info = $model->with('detail_info')->where(['id'=>$id])->find();
        json_return_code($info);
    }

    /**
     * 获取询价单信息
     * @return void
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function getInfo(){
        $id = input('id');
        $model = new BusInquiry();
        $info = $model->with('detail_info')->where(['id'=>$id])->find();
        json_return_code($info);
    }

    /**
     * 详情页面明细表
     * @return void
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function getPriceInfo()
    {
        $id = input('id');
        $model = new BusInquiry();
        $detailModel = new BusInquiryDetail();
        $supplierDetailModel = new BusInquiryDetailSupplier();
        $info = $model->field('id,bus_to_company_ids')->where(['id'=>$id])->find();
        /*$info['detail_info']= $detailModel->with(['suppliers'=>function ($query) use ($info) {
            $query->with('company')->where(['add_company_id'=>['in',$info['bus_to_company_ids']]]);
        }])->where(['bus_inquiry_id'=>$id])->select();*/
        $detail_info = $detailModel->where(['bus_inquiry_id'=>$id])->order('id asc')->select();
        $suppliers = $supplierDetailModel->with(['company','suppliersState'])->where(['bus_inquiry_id'=>$id,'add_company_id'=>['in',$info['bus_to_company_ids']]])->order('add_company_id asc,id asc')->select();
        $company_data = [];
        $totall = [];
        foreach ($suppliers as $item){
            $company_data[$item['bus_inquiry_detail_id']][] = $item;
            if(!isset($totall[$item['add_company_id']])){
                $totall[$item['add_company_id']]['id'] = -1;
                $totall[$item['add_company_id']]['bus_inquiry_id'] = $item['bus_inquiry_id'];
                $totall[$item['add_company_id']]['add_company_id'] = $item['add_company_id'];
                $totall[$item['add_company_id']]['bus_inquiry_suppliers_id'] = $item['bus_inquiry_suppliers_id'];
                $totall[$item['add_company_id']]['qulity_service_price'] = $item['state']>2?$item['qulity_service_price']:0;
                $totall[$item['add_company_id']]['qulity_org_price'] = $item['state']>2?$item['qulity_org_price']:0;
                $totall[$item['add_company_id']]['qulity_matching_price'] = $item['state']>2?$item['qulity_matching_price']:0;
                $totall[$item['add_company_id']]['qulity_complete_price'] = $item['state']>2?$item['qulity_complete_price']:0;
                $totall[$item['add_company_id']]['qulity_suitable_price'] = $item['state']>2?$item['qulity_suitable_price']:0;
            }else{
                $totall[$item['add_company_id']]['qulity_service_price'] += $item['state']>2?$item['qulity_service_price']:0;
                $totall[$item['add_company_id']]['qulity_org_price'] += $item['state']>2?$item['qulity_org_price']:0;
                $totall[$item['add_company_id']]['qulity_matching_price'] += $item['state']>2?$item['qulity_matching_price']:0;
                $totall[$item['add_company_id']]['qulity_complete_price'] += $item['state']>2?$item['qulity_complete_price']:0;
                $totall[$item['add_company_id']]['qulity_suitable_price'] += $item['state']>2?$item['qulity_suitable_price']:0;
            }
        }
        foreach ($detail_info as $item){
            $item['suppliers'] = $company_data[$item['id']];
        }
        $info['detail_info'] = $detail_info;
        $sum_num = $detailModel->where(['bus_inquiry_id'=>$id])->sum('num');
        ksort($totall);
        $info['all_info'] = [
                'id'=>-1,
                'eq_name'=>'合计',
                'num'=>$sum_num,
                'suppliers'=>array_values($totall)
            ];
        json_return_code($info);
    }

    /**
     * 询价详情表
     * @return void
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function getQutationInfo()
    {
        $id = input('id');
        $model = new BusInquiry();
        $supplierModel = new SuppliersCompany();
        $info = $model->where(['id'=>$id])->find();
        $info['suppliers'] = $supplierModel->where(['id'=>['in',$info['bus_to_company_ids']]])->field('id,suppliers_company_name')->select();

        $configModel = new SysConfig();
        $tax =  $configModel->where(['name'=>'tax'])->find();
        $info['sys_tax_rate'] = $tax['val']['content'];
        json_return_code($info);
    }

    public function getSupplierPrice()
    {
        $id = input('id');
        $supplier_id =input('supplier_id');
        // $profit_rate =input('profit_rate',0);
        $org_profit_rate =input('org_profit_rate',0)?:0;
        $matching_profit_rate =input('matching_profit_rate',0)?:0;
        $complete_profit_rate =input('complete_profit_rate',0)?:0;
        $suitable_profit_rate =input('suitable_profit_rate',0)?:0;
        $param = ['bus_inquiry_id'=>$id,'add_company_id'=>$supplier_id];
        $supplierDetailModel = new BusInquiryDetailSupplier();
        $sum_num = $supplierDetailModel->where($param)->sum('num');
        $detail_info= $supplierDetailModel->with(['company','detail'])->where($param)->order('order_no asc,id asc')->select();

        $qulity_service_price = 0;
        $qulity_org_price = 0;
        $qulity_matching_price = 0;
        $qulity_complete_price = 0;
        $qulity_suitable_price = 0;

        $quote_service_price = 0;
        $quote_org_price = 0;
        $quote_matching_price = 0;
        $quote_complete_price = 0;
        $quote_suitable_price = 0;

        foreach ($detail_info as $item){
            $item['qulity_service_price'] =$item['state']>2?$item['qulity_service_price']:0;
            $item['qulity_org_price'] = $item['state']>2?$item['qulity_org_price']:0;
            $item['qulity_matching_price'] = $item['state']>2?$item['qulity_matching_price']:0;
            $item['qulity_complete_price'] = $item['state']>2?$item['qulity_complete_price']:0;
            $item['qulity_suitable_price'] = $item['state']>2?$item['qulity_suitable_price']:0;

            $item['total_service_price'] = $item['qulity_service_price'];
            // $item['total_service_price'] = $item['detail']['qulity_service_price']>0?$item['detail']['qulity_service_price']:round(floatval($item['qulity_service_price'])*(100+$profit_rate)/100);
            $item['total_org_price']     = ($item['detail']['qulity_org_price']>0 || $item['detail']['qulity_org_price']===0)?$item['detail']['qulity_org_price']:round(floatval($item['qulity_org_price'])*(100+$org_profit_rate)/100);
            $item['total_matching_price'] = ($item['detail']['qulity_matching_price']>0 || $item['detail']['qulity_matching_price']===0)?$item['detail']['qulity_matching_price']:round(floatval($item['qulity_matching_price'])*(100+$matching_profit_rate)/100);
            $item['total_complete_price'] = ($item['detail']['qulity_complete_price']>0 || $item['detail']['qulity_complete_price']===0)?$item['detail']['qulity_complete_price']:round(floatval($item['qulity_complete_price'])*(100+$complete_profit_rate)/100);
            $item['total_suitable_price'] = ($item['detail']['qulity_suitable_price']>0 || $item['detail']['qulity_suitable_price']===0)?$item['detail']['qulity_suitable_price']:round(floatval($item['qulity_suitable_price'])*(100+$suitable_profit_rate)/100);
            $qulity_service_price += $item['qulity_service_price'];
            $qulity_org_price += $item['qulity_org_price'];
            $qulity_matching_price += $item['qulity_matching_price'];
            $qulity_complete_price += $item['qulity_complete_price'];
            $qulity_suitable_price += $item['qulity_suitable_price'];

            $quote_service_price += $item['total_service_price'];
            $quote_org_price += $item['total_org_price'];
            $quote_matching_price += $item['total_matching_price'];
            $quote_complete_price += $item['total_complete_price'];
            $quote_suitable_price += $item['total_suitable_price'];
        }
        $price_info['bus_inquiry_id'] = $id;
        $price_info['add_company_id'] = $supplier_id;
        $price_info['id'] = -1;
        $price_info['eq_name'] = '合计';
        $price_info['num'] = $sum_num;
        $price_info['qulity_service_price'] = round($qulity_service_price);
        $price_info['qulity_org_price'] = round($qulity_org_price);
        $price_info['qulity_matching_price'] = round($qulity_matching_price);
        $price_info['qulity_complete_price'] = round($qulity_complete_price);
        $price_info['qulity_suitable_price'] = round($qulity_suitable_price);
        $price_info['total_service_price'] = round($quote_service_price);
        $price_info['total_org_price'] = round($quote_org_price);
        $price_info['total_matching_price'] = round($quote_matching_price);
        $price_info['total_complete_price'] = round($quote_complete_price);
        $price_info['total_suitable_price'] = round($quote_suitable_price);
        $info['detail_info'] = $detail_info;
        $info['all_info'] = $price_info;
        json_return_code($info);
    }

    /**
     * 新增修改询价单信息
     * @return \think\response\Json
     */
    public function addInquiry(){
        $data = $this->trimParam();
        $model = new BusInquiry();
        $detailModel = new BusInquiryDetail();
        $suppliersInquiryDetailModel = new BusInquiryDetailSupplier();
        $detail_info = json_decode($data['detail_info'],true); // 详情
        $times = date('Y-m-d H:i:s');
        $inquiry_data = [
            'vehicle_frame_no'=>$data['vehicle_frame_no'],
            'vehicle_license_num'=>$data['vehicle_license_num'],
            'car_model'=>$data['car_model'],
            'brand_name'=>$data['brand_name'],
            'service_no'=>$data['service_no'],
            'deadline_datetime'=>$data['deadline_datetime']?$data['deadline_datetime'].':00:00':'',
            'bus_to_company_ids'=>$data['bus_to_company_ids'],
            'bus_from_company_id'=>$data['bus_from_company_id'],
            'bus_user_name'=>$data['bus_user_name'],
            'bus_user_phone'=>$data['bus_user_phone'],
            'repair_company_name'=>$data['repair_company_name'],
            'repair_company_phone'=>$data['repair_company_phone'],
            'common'=>$data['common'],
            'files'=>$data['files'],
            'file_name'=>$data['file_name'],
            'file_size'=>$data['file_size'],
            'add_user_id'=>$data['opt_user_id'],
            'add_user_name'=>$data['opt_user_name'],
            'add_datetime'=>$times,
        ];
        if(isset($data['id']) && $data['id']){
            $bus_inquiry_id = $data['id'];
        }else{
            $bus_inquiry_id = 0;
            $inquiry_data['bus_inquiry_no'] = 'XJ'.date('Ymd').intval(microtime(true)*1000);
        }

        $result = $this->validate($inquiry_data,'Inquiry.add');
        if ($result !== true) json_return_code('',$result,201);

        if(empty($detail_info)){
            json_return_code('','询价零件必填',201);
        }
        $salesCompanyModel = new SalesCompany();
        $inquiry_data['bus_from_company_name'] = $salesCompanyModel->where(['id'=>$data['bus_from_company_id']])->value('company_name');

        $suppliersCompanyModel = new SuppliersCompany();
        $suppliers_names = $suppliersCompanyModel->where(['id'=>['in',$data['bus_to_company_ids']]])->column('id,suppliers_company_name');
        $inquiry_data['bus_to_company_name'] = implode(',',$suppliers_names);

        $eq_name_arr = array_column($detail_info,'eq_name');
        $unique_eq_name_arr = array_unique($eq_name_arr);
        if(count($eq_name_arr) != count($unique_eq_name_arr)){
            json_return_code('','零件清单有重复数据，请核对',201);
        }
        if(in_array('',$unique_eq_name_arr)){
            json_return_code('','零件名称必填，请核对',201);
        }
        $model->startTrans();
        try{
            $has_eq_names = [];
            if($bus_inquiry_id){
                $has_inquiry_suppliers = $model->where(['id'=>$bus_inquiry_id])->value('bus_to_company_ids');
                $suppliers_names = $suppliersCompanyModel->where(['id'=>['in',$data['bus_to_company_ids'].',',$has_inquiry_suppliers]])->column('id,suppliers_company_name');
                $model->isUpdate(true)->save($inquiry_data,['id'=>$bus_inquiry_id]);
                $has_eq_names = $detailModel->where(['bus_inquiry_id'=>$bus_inquiry_id])->column('eq_name');
            }else{
                $bus_inquiry_id = $model->insertGetId($inquiry_data);
            }

            //处理详情表数据
            $detail_add_arr = [
                'bus_inquiry_id'=>$bus_inquiry_id,
                'add_user_id'=>$data['opt_user_id'],
                'add_user_name'=>$data['opt_user_name'],
                'add_datetime'=>$times,
                'state'=>1,
            ];
            $detail_info = array_map(function($item) use ($detail_add_arr) {
                $item['order_no'] = $item['eq_name']=='运费和木架'?999:1;
                return array_merge($item, $detail_add_arr);
            }, $detail_info);
            $detailModel->saveAll($detail_info);

            $delOilId = array_diff($has_eq_names,$eq_name_arr);
            if(!empty($delOilId)){
                $detailModel->where(['bus_inquiry_id'=>$bus_inquiry_id,'eq_name'=>['in',$delOilId]])->setField('delete_time',time());
                $suppliersInquiryDetailModel->where(['bus_inquiry_id'=>$bus_inquiry_id,'eq_name'=>['in',$delOilId]])->setField('delete_time',time());
            }

            $this->suppliersDataHandle($bus_inquiry_id,$suppliers_names);

            $model->commit();
            $inquiry_data['id'] = $bus_inquiry_id;
            $inquiry_data['detail_info'] = $detail_info;
            json_return_code($inquiry_data);
        }catch (Exception $e){
            $model->rollback();
            json_return_code('','提交失败'.$e->getMessage(),201);
        }
    }

    /**
     * 供应商对应处理（新增）
     * @param $bus_inquiry_id
     * @param $suppliers_names
     * @return true
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    private function suppliersDataHandle($bus_inquiry_id,$suppliers_names)
    {
        $suppliersInquiryModel = new BusInquirySuppliers();
        $suppliersInquiryDetailModel = new BusInquiryDetailSupplier();
        $inquiryModel = new BusInquiry();

        $data = $inquiryModel->with('detail_info')->where(['id'=>$bus_inquiry_id])->find();
        $suppliers_info = $suppliersInquiryModel->with('detail_info')->where(['bus_inquiry_id'=>$bus_inquiry_id])->select();

        $suppliers_info_arr = array_column($suppliers_info,null,'bus_to_company_id');

        $inquiry_data = [
            'bus_inquiry_id'=>$data['id'],
            'bus_inquiry_no'=>$data['bus_inquiry_no'],
            'vehicle_frame_no'=>$data['vehicle_frame_no'],
            'vehicle_license_num'=>$data['vehicle_license_num'],
            'car_model'=>$data['car_model'],
            'brand_name'=>$data['brand_name'],
            'service_no'=>$data['service_no'],
            'deadline_datetime'=>$data['deadline_datetime'].':00:00',
            'bus_from_company_id'=>$data['bus_from_company_id'],
            'bus_from_company_name'=>$data['bus_from_company_name'],
            'common'=>$data['common'],
            'bus_user_name'=>$data['bus_user_name'],
            'bus_user_phone'=>$data['bus_user_phone'],
            'repair_company_name'=>$data['repair_company_name'],
            'repair_company_phone'=>$data['repair_company_phone'],
            'add_user_id'=>$data['add_user_id'],
            'add_user_name'=>$data['add_user_name'],
            'add_datetime'=>$data['add_datetime'],
            'state'=>0
        ];
        $detail_info = [];
        foreach ($data['detail_info'] as $item){
            $detail_info[$item['id']] = [
                'bus_inquiry_detail_id'=>$item['id'],
                'bus_inquiry_id'=>$item['bus_inquiry_id'],
                'eq_name'=>$item['eq_name'],
                'oe_no'=>$item['oe_no'],
                'num'=>$item['num'],
                'qulity_service_state'=>$item['qulity_service_state'],
                'qulity_org_state'=>$item['qulity_org_state'],
                'qulity_matching_state'=>$item['qulity_matching_state'],
                'qulity_complete_state'=>$item['qulity_complete_state'],
                'qulity_suitable_state'=>$item['qulity_suitable_state'],
                // 'common'=>$item['common'],
                'state'=>1,
                'add_user_id'=>$data['add_user_id'],
                'add_user_name'=>$data['add_user_name'],
                'add_datetime'=>$data['add_datetime'],
            ];
        }
        foreach ($suppliers_names as $key=>$val){
            $inquiry_data['bus_to_company_id'] = $key;
            $inquiry_data['bus_to_company_name'] = $val;
            if(isset($suppliers_info_arr[$key])){
                $bus_inquiry_suppliers_id = $suppliers_info_arr[$key]['id'];
                $suppliersInquiryModel->save($inquiry_data,['id'=>$bus_inquiry_suppliers_id]);
                foreach($suppliers_info_arr[$key]['detail_info'] as $item){
                    if(isset($detail_info[$item['bus_inquiry_detail_id']])){
                        $detail_info[$item['bus_inquiry_detail_id']]['id'] = $item['id'];
                    }
                }
            }else{
                $bus_inquiry_suppliers_id = $suppliersInquiryModel->insertGetId($inquiry_data);
            }
            $detail_add_arr = [
                'bus_inquiry_suppliers_id'=>$bus_inquiry_suppliers_id,
                'add_company_id'=>$key,
            ];
            $detail_info = array_map(function($item) use ($detail_add_arr) {
                return array_merge($item, $detail_add_arr);
            }, $detail_info);
            $suppliersInquiryDetailModel->saveAll($detail_info);
        }
        return true;
    }

    /**
     * 编辑询价单详情
     * @return void
     * @throws PDOException
     */
    public function modifyInquiry(){
        $data = $this->trimParam();
        $model = new BusInquiry();
        $detailModel = new BusInquiryDetail();
        $suppliersInquiryModel = new BusInquirySuppliers();
        $suppliersInquiryDetailModel = new BusInquiryDetailSupplier();
        $detail_info = json_decode($data['detail_info'],true); // 详情
        $times = date('Y-m-d H:i:s');
        $inquiry_data = [
            'id'=>$data['id'],
            'vehicle_frame_no'=>$data['vehicle_frame_no'],
            'vehicle_license_num'=>$data['vehicle_license_num'],
            'car_model'=>$data['car_model'],
            'brand_name'=>$data['brand_name'],
            'service_no'=>$data['service_no'],
            'deadline_datetime'=>$data['deadline_datetime']?$data['deadline_datetime'].':00:00':'',
            'bus_to_company_ids'=>$data['bus_to_company_ids'],
            'bus_from_company_id'=>$data['bus_from_company_id'],
            'common'=>$data['common'],
            'add_user_id'=>$data['opt_user_id'],
            'add_user_name'=>$data['opt_user_name'],
            'bus_user_name'=>$data['bus_user_name'],
            'bus_user_phone'=>$data['bus_user_phone'],
            // 'repair_company_name'=>$data['repair_company_name'],
            // 'repair_company_phone'=>$data['repair_company_phone'],
            // 'sale_price_state'=>0,
            'state'=>1,
        ];
        if($data['add_state']){
            $inquiry_data['sale_price_state'] = 0;
        }
        $bus_inquiry_id = $data['id'];

        $result = $this->validate($inquiry_data,'Inquiry.update');
        if ($result !== true) json_return_code('',$result,201);
        unset($inquiry_data['id']);

        if(empty($detail_info)){
            json_return_code('','询价零件必填',201);
        }
        $salesCompanyModel = new SalesCompany();
        $inquiry_data['bus_from_company_name'] = $salesCompanyModel->where(['id'=>$data['bus_from_company_id']])->value('company_name');
        $data['bus_from_company_name'] = $inquiry_data['bus_from_company_name'];

        $suppliersCompanyModel = new SuppliersCompany();
        $suppliers_names = $suppliersCompanyModel->where(['id'=>['in',$data['bus_to_company_ids']]])->column('id,suppliers_company_name');
        $inquiry_data['bus_to_company_name'] = implode(',',$suppliers_names);

        $eq_name_arr = array_column($detail_info,'eq_name');
        $unique_eq_name_arr = array_unique($eq_name_arr);
        if(count($eq_name_arr) != count($unique_eq_name_arr)){
            json_return_code('','零件清单有重复数据，请核对',201);
        }
        if(in_array('',$unique_eq_name_arr)){
            json_return_code('','零件名称必填，请核对',201);
        }
        $model->startTrans();
        try{
            $has_inquiry_suppliers = $model->where(['id'=>$bus_inquiry_id])->value('bus_to_company_ids');
            // 平台总表
            $model->isUpdate(true)->save($inquiry_data,['id'=>$bus_inquiry_id]);
            $has_eq_ids = $detailModel->where(['bus_inquiry_id'=>$bus_inquiry_id])->column('id');

            // 供应商总表
            $suppliers_inquiry_data = $inquiry_data;
            unset($suppliers_inquiry_data['bus_to_company_name']);
            $suppliers_inquiry_data['update_time'] = $times;
            if($data['add_state']){
                $suppliers_inquiry_data['state'] = 0;
            }else{
                unset($suppliers_inquiry_data['state']);
            }
            $suppliersInquiryModel->isUpdate(true)->save($suppliers_inquiry_data,['bus_inquiry_id'=>$bus_inquiry_id]);
            $new_company_ids = explode(',',$data['bus_to_company_ids']);
            $old_company_ids = explode(',',$has_inquiry_suppliers);
            $delCompanyId = array_diff($old_company_ids,$new_company_ids);
            $addCompanyIds = array_diff($new_company_ids,$old_company_ids);
            $add_suppliers_names = $suppliersCompanyModel->where(['id'=>['in',$addCompanyIds]])->column('id,suppliers_company_name');
            if(!empty($delCompanyId)){
                $suppliersInquiryModel->where(['bus_inquiry_id'=>$bus_inquiry_id,'bus_to_company_id'=>['in',$delCompanyId]])->setField('delete_time',time());
            }
            //处理详情表数据
            $eq_id_arr = [];
            foreach ($detail_info as $key=>$item){
                if($item['eq_name'] === '合计'){
                    unset($detail_info[$key]);
                    continue;
                }
                if(!$detail_info[$key]['id']) unset($detail_info[$key]['id']);
                $detail_info[$key]['bus_inquiry_id'] = $bus_inquiry_id;
                $detail_info[$key]['add_user_id'] = $data['opt_user_id'];
                $detail_info[$key]['add_user_name'] = $data['opt_user_name'];
                $detail_info[$key]['add_datetime'] = $times;
                if(isset($detail_info[$key]['id']) && $detail_info[$key]['id']){
                    $eq_id_arr[] = $detail_info[$key]['id'];
                }
            }
            $detailModel->saveAll($detail_info);
            $delOilId = array_diff($has_eq_ids,$eq_id_arr);
            if(!empty($delOilId)){
                $detailModel->where(['bus_inquiry_id'=>$bus_inquiry_id,'id'=>['in',$delOilId]])->setField('delete_time',time());
                $suppliersInquiryDetailModel->where(['bus_inquiry_id'=>$bus_inquiry_id,'bus_inquiry_detail_id'=>['in',$delOilId]])->setField('delete_time',time());
            }
            $this->suppliersPriceHandle($data,$add_suppliers_names);
            $model->commit();
            $inquiry_data['id'] = $bus_inquiry_id;
            $inquiry_data['detail_info'] = $detail_info;
            addLog('修改询价单信息');
            json_return_code($inquiry_data);
        }catch (Exception $e){
            $model->rollback();
            json_return_code('','提交失败'.$e->getMessage(),201);
        }
    }

    /**
     * 编辑询价单
     * @param $data
     * @return true
     * @throws \Exception
     */
    private function suppliersPriceHandle($data,$add_suppliers_names)
    {
        $detailModel = new BusInquiryDetail();
        $suppliersInquiryModel = new BusInquirySuppliers();
        $suppliersInquiryDetailModel = new BusInquiryDetailSupplier();
        $details = $detailModel->where(['bus_inquiry_id'=>$data['id']])->column('eq_name,id');
        $suppliersInquiry = $suppliersInquiryModel->where(['bus_inquiry_id'=>$data['id']])->column('bus_to_company_id,id');
        $detail_info_ups = json_decode($data['detail_info'],true);
        $detail_info = [];
        foreach ($detail_info_ups as $key=>$item){
            if($item['eq_name'] === '合计'){
                unset($detail_info_ups[$key]);
                continue;
            }
            foreach ($item['suppliers'] as $supplier){
                $info = [
                    'add_company_id'=>$supplier['add_company_id'],
                    'bus_inquiry_suppliers_id'=>$supplier['bus_inquiry_suppliers_id']??$suppliersInquiry[$supplier['add_company_id']],
                    'bus_inquiry_detail_id'=>$supplier['bus_inquiry_detail_id']??$details[$item['eq_name']],
                    'bus_inquiry_id'=>$data['id'],
                    'eq_name'=>$item['eq_name'],
                    'oe_no'=>$supplier['oe_no']??'',
                    'common'=>$supplier['common']??'',
                    'num'=>$item['num'],
                    'state'=>$supplier['state']??1,
                    'qulity_service_state'=>$item['qulity_service_state'],
                    'qulity_org_state'=>$item['qulity_org_state'],
                    'qulity_matching_state'=>$item['qulity_matching_state'],
                    'qulity_complete_state'=>$item['qulity_complete_state'],
                    'qulity_suitable_state'=>$item['qulity_suitable_state'],
                    'qulity_service_common'=>$supplier['qulity_service_common']??'',
                    'qulity_org_common'=>$supplier['qulity_org_common']??'',
                    'qulity_matching_common'=>$supplier['qulity_matching_common']??'',
                    'qulity_complete_common'=>$supplier['qulity_complete_common']??'',
                    'qulity_suitable_common'=>$supplier['qulity_suitable_common']??'',
                ];
                if(isset($supplier['state']) && $supplier['state'] >2){
                    $info['qulity_service_price'] = $supplier['qulity_service_price']??0;
                    $info['qulity_org_price'] = $supplier['qulity_org_price']??0;
                    $info['qulity_matching_price'] = $supplier['qulity_matching_price']??0;
                    $info['qulity_complete_price'] = $supplier['qulity_complete_price']??0;
                    $info['qulity_suitable_price'] = $supplier['qulity_suitable_price']??0;
                }
                if($supplier['id']){
                    $info['id'] = $supplier['id'];
                }else{
                    $info['add_user_id'] = $data['opt_user_id'];
                    $info['add_user_name'] = $data['opt_user_name'];
                    $info['add_datetime'] = date('Y-m-d H:i:s');
                }
                $detail_info[] = $info;
            }
        }
        if($add_suppliers_names){
            $inquiry_data = [
                'bus_inquiry_id'=>$data['id'],
                'bus_inquiry_no'=>$data['bus_inquiry_no'],
                'vehicle_frame_no'=>$data['vehicle_frame_no'],
                'vehicle_license_num'=>$data['vehicle_license_num'],
                'car_model'=>$data['car_model'],
                'brand_name'=>$data['brand_name'],
                'service_no'=>$data['service_no'],
                'deadline_datetime'=>$data['deadline_datetime'].':00:00',
                'bus_from_company_id'=>$data['bus_from_company_id'],
                'bus_from_company_name'=>$data['bus_from_company_name'],
                'common'=>$data['common'],
                'bus_user_name'=>$data['bus_user_name'],
                'bus_user_phone'=>$data['bus_user_phone'],
                'repair_company_name'=>$data['repair_company_name']??'',
                'repair_company_phone'=>$data['repair_company_phone']??'',
                'add_user_id'=>$data['opt_user_id'],
                'add_user_name'=>$data['opt_user_name'],
                'add_datetime'=>date('Y-m-d H:i:s'),
                'state'=>0
            ];
            foreach ($add_suppliers_names as $key=>$val){
                $inquiry_data['bus_to_company_id'] = $key;
                $inquiry_data['bus_to_company_name'] = $val;
                $bus_inquiry_suppliers_id = $suppliersInquiryModel->insertGetId($inquiry_data);
                foreach ($detail_info_ups as $item){
                    $detail_info[] = [
                        'bus_inquiry_detail_id'=>$item['id'],
                        'bus_inquiry_id'=>$item['bus_inquiry_id'],
                        'eq_name'=>$item['eq_name'],
                        'oe_no'=>$item['oe_no'],
                        'num'=>$item['num'],
                        'qulity_service_state'=>$item['qulity_service_state'],
                        'qulity_org_state'=>$item['qulity_org_state'],
                        'qulity_matching_state'=>$item['qulity_matching_state'],
                        'qulity_complete_state'=>$item['qulity_complete_state'],
                        'qulity_suitable_state'=>$item['qulity_suitable_state'],
                        'state'=>1,
                        'add_user_id'=>$data['opt_user_id'],
                        'add_user_name'=>$data['opt_user_name'],
                        'add_datetime'=>date('Y-m-d H:i:s'),
                        'bus_inquiry_suppliers_id'=>$bus_inquiry_suppliers_id,
                        'add_company_id'=>$key,
                    ];
                }
            }
        }
        $suppliersInquiryDetailModel->saveAll($detail_info);
        return true;
    }

    /**
     * 生成报价单
     * @return void
     * @throws PDOException
     */
    public function createQuotation()
    {
        $data = $this->trimParam();
        $detail_info = json_decode($data['detail_info'],true);
        $detail_data = [];
        $supplier_data = [];
        foreach ($detail_info as $item){
            $detail_data[] = [
                'id'=>$item['bus_inquiry_detail_id'],
                'quote_quilty'=>$item['quote_quilty'],
                'add_company_id'=>$data['add_company_id'],
                'state'=>$item['quote_quilty']?3:2,
                'qulity_service_price'=>$item['total_service_price'],
                'qulity_org_price'=>$item['total_org_price'],
                'qulity_matching_price'=>$item['total_matching_price'],
                'qulity_complete_price'=>$item['total_complete_price'],
                'qulity_suitable_price'=>$item['total_suitable_price'],
            ];
            $supplier_data[] = [
                'id'=>$item['id'],
                'quote_quilty'=>$item['quote_quilty'],
            ];
        }

        $inquiryModel = new BusInquiry();
        $detailModel = new BusInquiryDetail();
        $supplierDetailModel = new BusInquiryDetailSupplier();
        try {
            $detailModel->startTrans();
            //询价单详情修改
            $detailModel->saveAll($detail_data);
            //供应商详情修改
            $supplierDetailModel->saveAll($supplier_data);

            $from_quotation_selection_json['add_company_id'] = $data['add_company_id'];
            $supplierModel = new SuppliersCompany();
            $from_quotation_selection_json['add_company_name'] = $supplierModel->where(['id'=>$data['add_company_id']])->value('suppliers_company_name');
            // $from_quotation_selection_json['profit_rate'] = $data['profit_rate'];
            $from_quotation_selection_json['org_profit_rate'] = $data['org_profit_rate']??'';
            $from_quotation_selection_json['matching_profit_rate'] = $data['matching_profit_rate']??'';
            $from_quotation_selection_json['complete_profit_rate'] = $data['complete_profit_rate']??'';
            $from_quotation_selection_json['suitable_profit_rate'] = $data['suitable_profit_rate']??'';
            $from_quotation_selection_json['eq_info'] = $detail_data;
            $inquiry_data = [
                'quote_datetime'=>date('Y-m-d H:i:s'),
                'tax_rate'=>$data['tax_rate']??'',
                'sale_price_state'=>1,
                'quote_company_name'=>$from_quotation_selection_json['add_company_name'],
                'quote_company_id'=>$data['add_company_id'],
                'from_quotation_selection_json'=>json_encode($from_quotation_selection_json), //供应商
                'to_quotation_selection_json'=>json_encode($supplier_data), //销售商
            ];
            $inquiryModel->isUpdate(true)->save($inquiry_data,['id'=>$data['id']]);
            $detailModel->commit();
            addLog('形成报价');
            //生成报价单文件
            json_return_code();
        }catch (Exception $e){
            $detailModel->rollback();
            json_return_code('','操作失败'.$e->getMessage(),201);
        }

    }

    /**
     * 生成报价文件
     * @return void
     */
    public function createQuotationFile()
    {
        $data = $this->trimParam();
        $inquiryModel = new BusInquiry();
        $inquiryModel->createQuotationFile($data);
    }

    /**
     * 确认中标完善报价信息
     * @return void
     */
    public function editQuotation()
    {
        $data = $this->trimParam();
        $id = $data['id'];
        $add_company_id = $data['add_company_id'];
        unset($data['id']);
        unset($data['add_company_id']);

        $data['sale_price_state'] = 2;
        $data['sure_user_id'] = $data['opt_user_id'];
        $data['sure_user_name'] = $data['opt_user_name'];
        $data['sure_datetime'] = date('Y-m-d H:i:s');
        $supplier_data = $data;
        $supplier_data['state'] = 5;
        $supplier_data['sure_datetime'] = date('Y-m-d H:i:s');
        $model = new BusInquiry();
        $supplierModel = new BusInquirySuppliers();
        try {
            $model->startTrans();
            $model->isUpdate(true)->save($data,['id'=>$id]);
            $supplierModel->isUpdate(true)->save($supplier_data,['bus_inquiry_id'=>$id,'bus_to_company_id'=>$add_company_id]);
            $supplierModel->isUpdate(true)->save([
                'state'=>7,
                'sure_datetime'=>date('Y-m-d H:i:s'),
            ],['bus_inquiry_id'=>$id,'bus_to_company_id'=>['<>',$add_company_id],'state'=>2]); //未中标
            $model->commit();
            json_return_code();
        }catch (\Exception $e){
            $model->rollback();
            json_return_code('','操作失败'.$e->getMessage(),201);
        }
    }

    public function createSalesPurchaseOrder()
    {
        $data = $this->trimParam();
        $detail_data = [];
        $supplier_detail_date = [];
        $detail_totall_price = 0;
        $supplier_totall_price = 0;

        $inquiryModel = new BusInquiry();
        $supplierCompanyModel = new SuppliersCompany();
        $supplier_tax_rate = $supplierCompanyModel->where(['id'=>$data['add_company_id']])->value('tax_rate');
        $detail_infos = json_decode($data['detail_info'],true);
        foreach ($detail_infos as $item){
            if(!$item['detail']['sale_use_quilty'] && count($item['detail']['quote_quilty']) == 1){
               $item['detail']['sale_use_quilty'] = $this->quiltyChoose[$item['detail']['quote_quilty'][0]];
            }
            if(!$item['make_sure_quilty'] && count($item['detail']['quote_quilty']) == 1){
                $item['make_sure_quilty'] = $this->quiltyChoose[$item['detail']['quote_quilty'][0]];
            }
            /*if(!$item['make_sure_quilty'] || !$item['detail']['sale_use_quilty']){
                json_return_code('','请确认'.$item['eq_name'].'采用的品质',201);
            }*/
            $supplier_quilty = $item['make_sure_quilty'];
            $detail_quilty = $item['detail']['sale_use_quilty'];
            if($supplier_quilty){
                $supplier_info = [
                    'id'=>$item['id'],
                    'state'=>5,
                    'make_sure_quilty'=>$supplier_quilty,
                    'totall_price'=>round($item[$supplier_quilty]*$item['num']),

                ];
                $supplier_detail_date[] = $supplier_info;
                $supplier_totall_price += $supplier_info['totall_price'];
            }

            if($detail_quilty){
                $detail_info = [
                    'id'=>$item['detail']['id'],
                    'state'=>5,
                    'sale_use_quilty'=>$detail_quilty,
                    'totall_price'=>round($item['detail'][$detail_quilty]*$item['num']),
                ];
                $detail_data[] = $detail_info;
                $detail_totall_price += $detail_info['totall_price'];
            }
        }

        try {
            $inquiryModel->startTrans();
            $detailModel = new BusInquiryDetail();
            $supplierModel = new BusInquirySuppliers();
            $supplierDetailModel = new BusInquiryDetailSupplier();

            $inquiry_data = [
                'totall_price'=>$detail_totall_price,
                'sale_price_state'=>3
            ];
            $supplier_data = [
                'totall_price'=>$supplier_totall_price,
                'tax_rate'=>$supplier_tax_rate,
                'state'=>6
            ];
            if(!$data['sales_no']){
                $sales_no = generateUniqueOrderno();
                $inquiry_data['sales_no']= $sales_no;
                $inquiry_data['sales_datetime']= date('Y-m-d H:i:s');
                $supplier_data['sales_no']= $sales_no;
                $supplier_data['sales_datetime']= date('Y-m-d H:i:s');
            }
            $inquiryModel->isUpdate(true)->save($inquiry_data,['id'=>$data['id']]);
            $detailModel->saveAll($detail_data);
            $supplierModel->isUpdate(true)->save($supplier_data,['bus_inquiry_id'=>$data['id'],'bus_to_company_id'=>$data['add_company_id']]);
            $supplierDetailModel->saveAll($supplier_detail_date);
            $inquiryModel->commit();
            json_return_code();
        }catch (\Exception $e){
            $inquiryModel->rollback();
            json_return_code('','操作失败'.$e->getMessage(),201);
        }
    }

    public function createSalesPurchaseFile()
    {
        $data = $this->trimParam();
        $inquiryModel = new BusInquiry();
        $inquiryModel->createSalesPurchaseFile($data);
    }
    /**
     * 报价价格修改
     * @return void
     */
    public function editPrice()
    {
        $data = $this->trimParam();
        $up_data[$data['tag_name']] = $data['price'];
        $detailModel = new BusInquiryDetail();
        $detailSupplierModel = new BusInquiryDetailSupplier();
        try {
            $detailModel->startTrans();
            if($data['tag_type'] === 'supplier'){
                if($data['tag_name'] == 'qulity_service_price'){
                    $detailModel->isUpdate(true)->save($up_data,['id'=>$data['detail_id']]);
                }
                $up_data['state'] = 3;
                $detailSupplierModel->isUpdate(true)->save($up_data,['id'=>$data['id']]);
            }else{
                $detailModel->isUpdate(true)->save($up_data,['id'=>$data['id']]);
                if($data['tag_name'] == 'qulity_service_price'){
                    $up_data['state'] = 3;
                    $detailSupplierModel->isUpdate(true)->save($up_data,['id'=>$data['detail_id']]);
                }
            }
            $detailModel->commit();
            addLog('修改询价单价格');
            json_return_code();
        }catch (Exception $e){
            $detailModel->rollback();
            json_return_code('','操作失败',201);
        }
    }
    /**
     * 修改供货商状态
     * @return void
     */
    public function changeState()
    {
        $id = input('id');
        $data['state'] = input('state');
        $model = new BusInquiry();
        if($data['state'] == 1){
            $deadline_datetime = $model->where(['id'=>$id])->value('deadline_datetime');
            if($deadline_datetime<= date('Y-m-d H:i:s')){
                $data['deadline_datetime'] = date('Y-m-d H', strtotime('+7 days', time())).':00:00';
            }
        }
        if($model->isUpdate(true)->save($data,['id'=>$id]) !== false){
            addLog('修改询价单状态');
            json_return_code($model->find($id));
        }else{
            json_return_code('','操作失败',201);
        }
    }

    /**
     * 再次报价
     * @return void
     * @throws PDOException
     */
    public function againInquiry()
    {
        $id = input('id');
        $model = new BusInquiry();
        $detailModel = new BusInquiryDetail();
        $supplierModel = new BusInquirySuppliers();
        $supplierDetailModel = new BusInquiryDetailSupplier();

        try {
            $model->startTrans();
            $model->where(['id'=>$id])->setField('sale_price_state',0);
            $detailModel->where(['bus_inquiry_id'=>$id])->setField('state',1);
            $supplierModel->where(['bus_inquiry_id'=>$id])->setField('state',0);
            $supplierDetailModel->where(['bus_inquiry_id'=>$id])->setField('state',1);
            $model->commit();
            json_return_code();
        }catch (Exception $e){
            $model->rollback();
            json_return_code('','操作失败',201);
        }
    }
    /**
     * 删除
     */
    public function del(){
        $id = input('id');
        $model = new BusInquiry();
        //1 参数验证是否合法
        if (empty($id)){
            json_return_code('',"ID不能为空！请检查",'201');
        }
        $model::destroy($id);
        $suppliersInquiryModel = new BusInquirySuppliers();
        $suppliersInquiryModel->where(['bus_inquiry_id'=>$id])->setField('delete_time',time());
        addLog('删除询价单信息');
        json_return_code('','删除成功');
    }

    /**
     * 修改报价所选品质
     * @return void
     * @throws PDOException
     */
    public function editQuoteQuilty()
    {
        $data = input();
        $detailModel = new BusInquiryDetail();
        $supplierDetailModel = new BusInquiryDetailSupplier();
        try {
            $detailModel->startTrans();
            //询价单详情修改
            $detailModel->isUpdate(true)->save(['quote_quilty'=>$data['quote_quilty']],['id'=>$data['bus_inquiry_detail_id']]);
            //供应商详情修改
            $supplierDetailModel->isUpdate(true)->save(['quote_quilty'=>$data['quote_quilty']],['id'=>$data['id']]);

            $detailModel->commit();
            addLog('修改报价品质');
            //生成报价单文件
            json_return_code();
        }catch (Exception $e){
            $detailModel->rollback();
            json_return_code('','操作失败'.$e->getMessage(),201);
        }
    }

    /**
     * 选择报价品质全部零件
     * @return void
     * @throws PDOException
     */
    public function editAllQuoteQuilty()
    {
        $data = input();
        $detailModel = new BusInquiryDetail();
        $supplierDetailModel = new BusInquiryDetailSupplier();
        try {
            $detailModel->startTrans();
            //询价单详情修改
            $detailModel->isUpdate(true)->save(['quote_quilty'=>$data['quote_quilty']],['bus_inquiry_id'=>$data['id']]);
            //供应商详情修改
            $supplierDetailModel->isUpdate(true)->save(['quote_quilty'=>$data['quote_quilty']],['bus_inquiry_id'=>$data['id'],'add_company_id'=>$data['supplier_id']]);

            $detailModel->commit();
            addLog('修改报价品质');
            //生成报价单文件
            json_return_code();
        }catch (Exception $e){
            $detailModel->rollback();
            json_return_code('','操作失败'.$e->getMessage(),201);
        }
    }
    /**
     * 退回配件商报价
     * @return void
     * @throws PDOException
     */
    public function returnSuppliersQuote()
    {
        $data = input();
        $supplierModel = new BusInquirySuppliers();
        $supplierDetailModel = new BusInquiryDetailSupplier();
        try {
            $supplierModel->startTrans();
            //询价单详情修改
            $supplierModel->isUpdate(true)->save(['state'=>3],['bus_inquiry_id'=>$data['id'],'bus_to_company_id'=>$data['bus_to_company_id']]);
            //供应商详情修改
            $supplierDetailModel->isUpdate(true)->save(['state'=>2],['bus_inquiry_id'=>$data['id'],'add_company_id'=>$data['bus_to_company_id']]);
            $supplierModel->commit();
            addLog('退回供应商报价');
            //生成报价单文件
            json_return_code();
        }catch (Exception $e){
            $supplierModel->rollback();
            json_return_code('','操作失败'.$e->getMessage(),201);
        }
    }

    /**
     * 修改业务员
     * @return void
     * @throws PDOException
     */
    public function changeUser()
    {
        $data = input();
        $userModel = new SysUser();
        $inquiryModel = new BusInquiry();
        $detailModel = new BusInquiryDetail();
        $supplierModel = new BusInquirySuppliers();
        $supplierDetailModel = new BusInquiryDetailSupplier();
        try {
            $supplierModel->startTrans();
            $user_name = $userModel->where(['user_id'=>$data['add_user_id']])->value('true_name');
            $up_data = [
                'add_user_id'=>$data['add_user_id'],
                'add_user_name'=>$user_name
            ];
            $inquiryModel->isUpdate(true)->save($up_data,['id'=>$data['id']]);
            //询价单详情修改
            $detailModel->isUpdate(true)->save($up_data,['bus_inquiry_id'=>$data['id']]);
            $supplierModel->isUpdate(true)->save($up_data,['bus_inquiry_id'=>$data['id']]);
            //供应商详情修改
            $supplierDetailModel->isUpdate(true)->save($up_data,['bus_inquiry_id'=>$data['id']]);
            $supplierModel->commit();
            addLog('修改业务员');
            //生成报价单文件
            json_return_code();
        }catch (Exception $e){
            $supplierModel->rollback();
            json_return_code('','操作失败'.$e->getMessage(),201);
        }
    }
}